/** 
  成绩相关设置
*/
<template>
  <div class="score-related-setting-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="$t('gradeRelatedSetting.gradeRecordMethod')" name="first">
        <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
          <div class="float-left" style="margin-bottom: 20px;">
            <el-input
              v-model="queryForm.gradeNameCn"
              :placeholder="$t('gradeRelatedSetting.searchName')"
              style="width:250px"
              clearable
              @keyup.enter.native="onSubmit">
                <i slot="suffix"
                  class="el-icon-search"
                  style="margin-top:10px;cursor:pointer"
                  @click="onSubmit">
                </i>
            </el-input>
          </div>
          <div class="float-right">
            <el-button v-if="permitToDelete" type="danger" @click="deleteData()">{{ $t('common.btn.delete') }}</el-button>
            <el-button v-if="permitToAdd" type="primary" @click="addData()">{{ $t('common.btn.add') }}</el-button>
          </div>
          <edu-table 
            ref="relatedSetting" 
            :selection="true"
            :pagination="false" 
            :order='false' 
            :tooltipEffect="tooltipEffect" 
            stripe 
            :data="dataList" 
            size="mini"
            @selection-change="handleSelectionChange">
              <edu-table-column :label="$t('gradeRelatedSetting.gradeNameCn')" prop="gradeNameCn"></edu-table-column>
              <edu-table-column :label="$t('gradeRelatedSetting.gradeNameEn')" prop="gradeNameEn"></edu-table-column>
              <edu-table-column :label="$t('gradeRelatedSetting.gradePassLine')" prop="gradePassLine"></edu-table-column>
              <edu-table-column :label="$t('common.text.operation')" prop="operation" fit>
                <template slot-scope="scope">
                  <el-button v-if="permitToEdit" type="text" @click="editData(scope.row)">{{ $t('common.btn.edit') }}</el-button>
                  <el-button v-if="permitToSelect" type="text" @click="selectData(scope.row)">{{ $t('message.Look') }}</el-button>
                </template>
              </edu-table-column>
          </edu-table>
          <el-row type="flex" class="row-bg" justify="end">
            <el-col>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryForm.pageNum_"
                :page-sizes="[20, 40, 80, 100]"
                :page-size="queryForm.pageSize_"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryForm.total_"
                style="float:right;margin-top:10px"
              ></el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>
      <el-tab-pane :label="$t('gradeRelatedSetting.globalSet')" name="second">
        <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
          <el-form :model="globalForm" class="globalForm" label-position="right" ref="globalForm" label-width="170px">
            <el-row>
              <el-col :span="24">
                <!-- 最终成绩来源 -->
                <el-form-item
                  :label="$t('gradeRelatedSetting.finalGrade') + '：'"
                  prop="finalGrade"
                  ref="finalGrade"
                  :rules="[{ required: true, message: $t('gradeRelatedSetting.requireFinalGrade'), trigger: 'blur' }]">
                  <el-transfer v-model="globalForm.finalGrade" @change="(value) => changeTransfer(value, 'finalGrade')" :data="options.finalGrade"></el-transfer>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <!-- 总评成绩成分 -->
                <el-form-item
                  :label="$t('gradeRelatedSetting.totalGrade') + '：'"
                  prop="totalGrade"
                  ref="totalGrade"
                  :rules="[{ required: true, message: $t('gradeRelatedSetting.requireTotalGrade'), trigger: 'blur' }]">
                  <el-transfer v-model="globalForm.totalGrade" @change="(value) => changeTransfer(value, 'totalGrade')" :data="options.totalGrade"></el-transfer>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <!-- 可发布成绩类型 -->
                <el-form-item 
                  :label="$t('gradeRelatedSetting.publishGrade') + '：'"
                  prop="publishGrade"
                  ref="publishGrade"
                  :rules="[{ required: true, message: $t('gradeRelatedSetting.requirePublishGrade'), trigger: 'blur' }]">
                  <el-transfer v-model="globalForm.publishGrade" @change="(value) => changeTransfer(value, 'publishGrade')" :data="options.publishGrade"></el-transfer>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <!-- 不给成绩的考试情况 -->
                <el-form-item 
                  :label="$t('gradeRelatedSetting.withoutGrade') + '：'"
                  prop="withoutGrade"
                  ref="withoutGrade"
                  :rules="[{ required: true, message: $t('gradeRelatedSetting.requireWithoutGrade'), trigger: 'blur' }]">
                  <el-transfer v-model="globalForm.withoutGrade" @change="(value) => changeTransfer(value, 'withoutGrade')" :data="options.withoutGrade"></el-transfer>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 允许重考的考试情况 -->
            <!-- <el-row>
              <el-col :span="24">
                <el-form-item 
                  :label="$t('gradeRelatedSetting.allowResetExam') + '：'"
                  prop="allowResetExam"
                  ref="allowResetExam"
                  :rules="[{ required: true, message: $t('gradeRelatedSetting.requireAllowResetExam'), trigger: 'blur' }]">
                  <el-transfer v-model="globalForm.allowResetExam" @change="(value) => changeTransfer(value, 'allowResetExam')" :data="options.allowResetExam"></el-transfer>
                </el-form-item>
              </el-col>
            </el-row> -->
            <el-row>
              <el-col :span="24">
                <!-- 是否验证短信信息 -->
                <el-form-item 
                  :label="$t('gradeRelatedSetting.isCheckMsg') + '：'"
                  prop="isCheckMsg">
                  <div style="display: inline-block;width: 100%;">
                    <el-radio v-model="globalForm.isCheckMsg" label="Y">{{ $t('externamExchangeBase.yes') }}</el-radio>
                    <el-radio v-model="globalForm.isCheckMsg" label="N">{{ $t('externamExchangeBase.no') }}</el-radio>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <div style="width: 100%;text-align: right;">
              <el-button @click="resetData()">{{ $t('common.btn.reset') }}</el-button>
              <el-button type="primary" @click="saveData()">{{ $t('common.btn.save') }}</el-button>
            </div>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :before-close="beforeClose"
      :title="title"
      width="70%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogForm" label-position="right" ref="dialogForm" label-width="120px">
        <el-row>
          <el-col :span="8">
            <!-- 中文名称 -->
            <el-form-item
              :label="$t('gradeRelatedSetting.gradeNameCn') + '：'"
              prop="gradeNameCn"
              :rules="[{ required: true, message: $t('gradeRelatedSetting.requireGradeNameCn'), trigger: 'blur' }]">
              <el-select v-model="dialogForm.gradeNameCn" @change="changeGradeNameCn" :disabled="dialogMode === 'select'" :placeholder="$t('common.pla.pleaseSelect')" clearable style="width: 100%;">
                <el-option
                  v-for="item in options.gradeNameCn"
                  :key="item.key"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 英文名称 -->
            <el-form-item 
              :label="$t('gradeRelatedSetting.gradeNameEn') + '：'"
              prop="gradeNameEn"
              :rules="[{ validator: checkSpecial, trigger: 'blur'}]">
              <el-input disabled v-model="dialogForm.gradeNameEn" :maxlength="128" clearable style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 及格线 -->
            <el-form-item 
              :label="$t('gradeRelatedSetting.gradePassLine') + '：'"
              prop="gradePassLine"
              :rules="[{ required: true, message: $t('gradeRelatedSetting.requireGradePassLine'), trigger: 'blur' },{ validator: validateGradePassLine, trigger: 'blur'}, { validator: checkSpecial, trigger: 'blur'}]">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="dialogForm.gradePassLine" :disabled="dialogMode === 'select'" :maxlength="5" clearable style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="padding: 15px 0;border-top: 1px solid #e5e5e5;">
            <div class="float-right" v-if="dialogMode === 'add' || dialogMode === 'edit'">
              <el-button @click="addGrade()">{{ $t('common.btn.add') }}</el-button>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <edu-table :pagination="false" :order='false' :selection="false" :tooltipEffect="tooltipEffect" stripe :data="dialogForm.minorGradeRelatedSetDetailsList" size="mini">
              <edu-table-column 
                :label="$t('ID')" 
                prop="scoreNum"
                v-if="dialogForm.gradeNameCn">
              </edu-table-column>
              <edu-table-column 
                :label="$t('gradeRelatedSetting.scoreName')" 
                prop="scoreName">
                <template slot-scope="scope">
                  <!-- 分数名称 -->
                  <el-form-item
                    style="margin-top: 15px;" 
                    :prop="'minorGradeRelatedSetDetailsList.' + scope.$index + '.scoreName'" 
                    label-width="0"
                    :rules="[{required: true, message: $t('gradeRelatedSetting.requireScoreName'), trigger: 'blur'},{ validator: checkSpecial, trigger: 'blur'}]">
                    <el-input v-model.trim="scope.row.scoreName" :disabled="dialogMode === 'select'" :maxlength="20" clearable :placeholder="$t('common.pla.pleaseInput')"></el-input>
                  </el-form-item>
                </template>
              </edu-table-column>
              <edu-table-column 
                :label="$t('gradeRelatedSetting.scoreMin')" 
                prop="scoreMin">
                <template slot-scope="scope">
                  <!-- 最小值（含） -->
                  <el-form-item
                    style="margin-top: 15px;" 
                    :prop="'minorGradeRelatedSetDetailsList.' + scope.$index + '.scoreMin'" 
                    label-width="0"
                    :rules="[{ validator: validateScoreMin, trigger: 'blur'}, { validator: checkSpecial, trigger: 'blur'}]">
                    <el-input v-model.trim="scope.row.scoreMin" :maxlength="5" :disabled="dialogMode === 'select'" clearable :placeholder="$t('common.pla.pleaseInput')"></el-input>
                  </el-form-item>
                </template>
              </edu-table-column>
              <edu-table-column 
                :label="$t('gradeRelatedSetting.scoreMax')" 
                prop="scoreMax">
                <template slot-scope="scope">
                  <!-- 最大值（含） -->
                  <el-form-item
                    style="margin-top: 15px;" 
                    :prop="'minorGradeRelatedSetDetailsList.' + scope.$index + '.scoreMax'" 
                    label-width="0"
                    :rules="[{ validator: validateScoreMax, trigger: 'blur'}, { validator: checkSpecial, trigger: 'blur'}]">
                    <el-input v-model.trim="scope.row.scoreMax" :maxlength="5" :disabled="dialogMode === 'select'" clearable :placeholder="$t('common.pla.pleaseInput')"></el-input>
                  </el-form-item>
                </template>
              </edu-table-column>
              <edu-table-column 
                :label="$t('gradeRelatedSetting.scoreDefault')" 
                prop="scoreDefault">
                <template slot-scope="scope">
                  <!-- 默认值 -->
                  <el-form-item 
                    style="margin-top: 15px;" 
                    :prop="'minorGradeRelatedSetDetailsList.' + scope.$index + '.scoreDefault'" 
                    label-width="0"
                    :rules="[{ validator: validateScoreDefault, trigger: 'blur'}, { validator: checkSpecial, trigger: 'blur'}]">
                    <el-input v-model.trim="scope.row.scoreDefault" :disabled="dialogMode === 'select'" :maxlength="5" clearable :placeholder="$t('common.pla.pleaseInput')"></el-input>
                  </el-form-item>
                </template>
              </edu-table-column>
              <edu-table-column 
                :label="$t('gradeRelatedSetting.gradePoint')" 
                prop="gradePoint">
                <template slot-scope="scope">
                  <!-- 绩点 -->
                  <el-form-item
                    style="margin-top: 15px;" 
                    :prop="'minorGradeRelatedSetDetailsList.' + scope.$index + '.gradePoint'" 
                    label-width="0"
                    :rules="[{ validator: validateGradePoint, trigger: 'blur'}, { validator: checkSpecial, trigger: 'blur'}]">
                    <el-input v-model.trim="scope.row.gradePoint" :disabled="dialogMode === 'select'" :maxlength="5" clearable :placeholder="$t('common.pla.pleaseInput')"></el-input>
                  </el-form-item>
                </template>
              </edu-table-column>
              <edu-table-column :label="$t('common.text.operation')" fit prop="operate" v-if="dialogMode === 'add' || dialogMode === 'edit'">
                <template slot-scope="props">
                  <el-button type="text" v-if="dialogForm.minorGradeRelatedSetDetailsList.length > 1" @click="deleteGrade(props.row)">{{ $t('common.btn.delete') }}</el-button>
                </template>
              </edu-table-column>
            </edu-table>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <template v-if="dialogMode === 'add' || dialogMode === 'edit'">
          <el-button @click="cancel('dialogForm')">{{ $t('common.btn.cancel') }}</el-button>
          <el-button type="primary" @click="confirm('dialogForm')">{{ $t('common.btn.confirm') }}</el-button>
        </template>
        <template v-else>
          <el-button @click="cancel('dialogForm')">{{ $t('common.btn.close') }}</el-button>
        </template>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import UTILS from "common/src/utils/utils";
import { queryDic } from "common/src/api/dictionary";
import scoreManagementApi from 'common/src/api/scoreManagement/scoreManagement';
export default {
  components: {
    
  },
  data () {
    return {
      activeName: 'first',
      auths: [],
      userInfo: {},
      permitToAdd: false,
      permitToDelete: false,
      permitToEdit: false,
      permitToSelect: false,
      queryForm: {
        "gradeNameCn": "",
        "pageNum_": 1,
        "pageSize_": 20,
        "total_": 0
      },
      options: {
        gradeNameCn: [],
        gradeNameEn: [],
        finalGrade: [],
        totalGrade: [],
        publishGrade: [],
        withoutGrade: [],
        allowResetExam: []
      },
      dataList: [],
      multipleSelection: [],
      dialogVisible: false,
      title: '',
      dialogForm: {
        gradeNameCn: '',
        gradeNameEn: '',
        gradePassLine: '',
        minorGradeRelatedSetDetailsList: [
         
        ]
      },
      dialogMode: '',
      globalForm: {
        finalGrade: [],
        totalGrade: [],
        publishGrade: [],
        withoutGrade: [],
        allowResetExam: [],
        isCheckMsg: 'Y'
      },
      globalSetArr: []
    }
  },
  filters: {
    
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths
      }
      if (JSON.parse(localStorage.getItem("sessiondata")).mockUser) {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).mockUser
      } else {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).user
      }
    }
    this.initOptions()
    this.onSubmit()
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    // 校验及格线，最多5位数，最多保留1位小数点，最大100
    validateGradePassLine(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1})?$/
      if (Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.lessThanMax')))
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateGrade')))
      } else {
        callback()
      }
    },
    // 校验最小值，最多5位数，最多保留1位小数点，最大100
    validateScoreMin(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1,2})?$/
      if (!value && value !== 0) {
        callback(new Error(this.$t('gradeRelatedSetting.requireScoreMin')))
      } else if (Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.lessThanMax')))
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateGrades')))
      } else {
        callback()
      }
    },
    // 校验最大值，最多5位数，最多保留1位小数点，最大100
    validateScoreMax(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1,2})?$/
      if (!value && value !== 0) {
        callback(new Error(this.$t('gradeRelatedSetting.requireScoreMax')))
      } else if (Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.lessThanMax')))
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateGrades')))
      } else {
        callback();
      }
    },
    // 校验默认值，最多65位数，最多保留1位小数点，最大100
    validateScoreDefault(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1})?$/
      if (!value && value !== 0) {
        callback(new Error(this.$t('gradeRelatedSetting.requireScoreDefault')))
      } else if (Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.lessThanMax')))
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateGrade')))
      } else {
        callback()
      }
    },
    // 校验绩点，最多5位数，最多保留1位小数点，最大100
    validateGradePoint(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1})?$/
      if (!value && value !== 0) {
        callback(new Error(this.$t('gradeRelatedSetting.requireGradePoint')))
      } else if (Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.lessThanMax')))
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateGrade')))
      } else {
        callback()
      }
    },
    initOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: [
          "X_CJJL_FX", // 中文名称
          "X_ZZCJLY_FX", // 最终成绩来源
          "X_ZPCJCF_FX", // 总评成绩成分
          "X_FBCJLX_FX", // 可发布成绩类型
          "X_YXCK_FX", // 不给成绩的考试情况
          "X_BGCJ_FX" // 允许重考的考试情况
        ]
      }
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            gradeNameCn: "X_CJJL_FX", // 中文名称
            finalGrade: "X_ZZCJLY_FX", // 最终成绩来源
            totalGrade: "X_ZPCJCF_FX", // 总评成绩成分
            publishGrade: "X_FBCJLX_FX", // 可发布成绩类型
            withoutGrade: "X_YXCK_FX", // 不给成绩的考试情况
            allowResetExam: "X_BGCJ_FX" // 允许重考的考试情况
          },
          res.data,
          this.options
        )
        this.options.totalGrade = this.options.totalGrade.filter(value => {
          return value.value === '11005' || value.value === '11006' || value.value === '11007' || value.value === '11008'
        })
      })
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    selectGlobalSetInfo() {
      scoreManagementApi.queryGlobalSetInfo({
        "manageDeptId": this.userInfo.currentManageDptId
      }).then(res => {
        if (res.code === 200) {
          if (res.data.length > 0) {
            this.globalSetArr = JSON.parse(JSON.stringify(res.data))
            if (this.globalSetArr.length > 0) {
              this.globalForm.isCheckMsg = this.globalSetArr[0].isCheckMsg
              this.globalSetArr.map(value => {
                this.globalForm[value.setType] = value.setContentCode.split(',')
              })
            }
          }
        }
      })
    },
    getListData() {
      this.queryForm.gradeNameCn = this.queryForm.gradeNameCn.trim()
      scoreManagementApi.getScoreRecordMethodList(this.queryForm).then((res) => {
        this.dataList = res.data.list
        this.queryForm.total_ = res.data.total_
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    },
    reset() {
      this.baseLevel = []
      Object.keys(this.queryForm.condition).forEach(key => this.queryForm.condition[key] = '')
      this.onSubmit()
    },
    handleClick() {
      if (this.activeName === 'first') {
        this.onSubmit()
      } else {
        this.$refs['globalForm'].resetFields()
        this.selectGlobalSetInfo()
      }
    },
    // 选择中文名称
    changeGradeNameCn(val) {
      // 筛选条件字典查询
      let data = {
        lang: "en",
        type: "allChild",
        keys: [
          "X_CJJL_FX" // 英文名称
        ]
      }
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            gradeNameEn: "X_CJJL_FX"
          },
          res.data,
          this.options
        )
        let targetArr = this.options.gradeNameEn.filter(value => {
          return value.value === val.toString()
        })
        if (targetArr.length > 0) {
          this.dialogForm.gradeNameEn = targetArr[0].label
        }
      })
      if(this.dialogMode === 'add'){
          if(this.dialogForm.gradeNameCn === '1001'){
              this.$set(this.dialogForm.minorGradeRelatedSetDetailsList[0],'scoreNum',1)
              this.$set(this.dialogForm.minorGradeRelatedSetDetailsList[1],'scoreNum',2)
              this.scoreNum100=[]
              this.dialogForm.minorGradeRelatedSetDetailsList.forEach((val,itm)=>{
                  this.scoreNum100.push(val.scoreNum)
              })
          }
          if(this.dialogForm.gradeNameCn === '1002'){
              this.$set(this.dialogForm.minorGradeRelatedSetDetailsList[0],'scoreNum',-1)
              this.$set(this.dialogForm.minorGradeRelatedSetDetailsList[1],'scoreNum',-2)
              this.scoreNum5=[]
              this.dialogForm.minorGradeRelatedSetDetailsList.forEach((val,itm)=>{
                  this.scoreNum5.push(val.scoreNum)
              })
          }
          if(this.dialogForm.gradeNameCn === '1003'){
              this.$set(this.dialogForm.minorGradeRelatedSetDetailsList[0],'scoreNum',-4)
              this.$set(this.dialogForm.minorGradeRelatedSetDetailsList[1],'scoreNum',-5)
              this.scoreNum2=[]
              this.dialogForm.minorGradeRelatedSetDetailsList.forEach((val,itm)=>{
                  this.scoreNum2.push(val.scoreNum)
              })
          }
      }
    },
    // 选择全局设置
    changeTransfer(val, ref) {
      if (val.length > 0) {
        this.$refs[ref].clearValidate()
      }
    },
    // 删除
    deleteData() {
      if (this.multipleSelection.length > 0) {
        let deleteArray = []
        this.multipleSelection.map(value => {
          deleteArray.push(value.gradeSetId)
        })
        this.$delConfirm().then(_ => {
          scoreManagementApi.deleteScoreRecordMethod({
            "gradeSetIds": deleteArray
          }).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success', 
                message: this.$t('scoreMangementBase.deleteSuccessfully')
              })
              this.onSubmit();
            }
          })
        })
      } else {
        this.$message(this.$t('graduateBase.pleaseChoose'));
      }
    },
    // 新增
    addData() {
      this.dialogMode = 'add'
      this.title = this.$t('gradeRelatedSetting.addScoreRecordMethod')
      this.$nextTick(() => {
        this.addGrade()
      })
      this.addGrade()
      this.dialogVisible = true
    },
    // 编辑
    editData(row) {
      this.editScoreNum5 = [-1, -2, -3, -4, -5] // 五分制
      this.editScoreNum2 = [-4, -5] // 两分制
      this.editScoreNum100 = [1, 2, 3, 4, 5] // 百分制
      this.dialogMode = 'edit'
      this.title = this.$t('gradeRelatedSetting.editScoreRecordMethod')
      scoreManagementApi.getScoreRecordMethod({
        "gradeSetId": row.gradeSetId
      }).then(res => {
        if (res.code === 200) {
          this.dialogForm['gradeSetId'] = row.gradeSetId
          this.dialogForm.gradeNameCn = res.data.gradeNameCode
          this.dialogForm.gradeNameEn = res.data.gradeNameEn
          this.dialogForm.gradePassLine = res.data.gradePassLine
          if (res.data.minorGradeRelatedSetDetailsList.length > 0) {
            res.data.minorGradeRelatedSetDetailsList.map(value => {
              this.dialogForm.minorGradeRelatedSetDetailsList.push({
                "gradeSetDetailsId": value.gradeSetDetailsId,
                "scoreName": value.scoreName,
                "scoreMin": value.scoreMin,
                "scoreMax": value.scoreMax,
                "scoreDefault": value.scoreDefault,
                "gradePoint": value.gradePoint,
                "scoreNum": value.scoreNum
              })
              // if(this.dialogForm.gradeNameCn === '1001') {// 百分制
              //   this.editScoreNum100.push(value.scoreNum)
              // }else if(this.dialogForm.gradeNameCn === '1002') {// 五分制
              //   this.editScoreNum5.push(value.scoreNum)
              // }else if(this.dialogForm.gradeNameCn === '1003') {// 两分制
              //   this.editScoreNum2.push(value.scoreNum)
              // }
            })
          } else {
            this.dialogForm.minorGradeRelatedSetDetailsList = []
          }
          this.dialogVisible = true
        }
      })
    },
    // 查看
    selectData(row) {
      this.dialogMode = 'select'
      this.title = this.$t('gradeRelatedSetting.selectScoreRecordMethod')
      scoreManagementApi.getScoreRecordMethod({
        "gradeSetId": row.gradeSetId
      }).then(res => {
        if (res.code === 200) {
          this.dialogForm['gradeSetId'] = row.gradeSetId
          this.dialogForm.gradeNameCn = res.data.gradeNameCode
          this.dialogForm.gradeNameEn = res.data.gradeNameEn
          this.dialogForm.gradePassLine = res.data.gradePassLine
          if (res.data.minorGradeRelatedSetDetailsList.length > 0) {
            res.data.minorGradeRelatedSetDetailsList.map(value => {
              this.dialogForm.minorGradeRelatedSetDetailsList.push({
                "scoreName": value.scoreName,
                "scoreMin": value.scoreMin,
                "scoreMax": value.scoreMax,
                "scoreDefault": value.scoreDefault,
                "gradePoint": value.gradePoint,
                "scoreNum": value.scoreNum
              })
            })
          } else {
            this.dialogForm.minorGradeRelatedSetDetailsList = []
          }
          this.dialogVisible = true
        }
      })
    },
    // 关闭前回调
    beforeClose() {
      this.cancel()
    },
    compareArrayList(list1,listObj2){
        let newList=[]
        list1.forEach((val,itm)=>{
            let isExist=false
            listObj2.forEach((value,item)=>{
                if(item!= listObj2.length-1){
                   if(val==value.scoreNum){
                        isExist=true;
                        return false;
                    }
                }              
            })
            if(!isExist){
                newList.push(val)
            }
        })
        return newList;
    },
    addNewList(operationType,type,list,listObj){ 
        let length=listObj.length
        if(list.length === 0){
            if(type === 3){
                if(operationType === 'scoreRecordMethod'){
                    this.scoreNum5.push(this.scoreNum5[this.scoreNum5.length-1]-1)
                }else if(operationType === 'editScoreRecord'){
                    this.editScoreNum5.push(this.editScoreNum5[this.editScoreNum5.length-1]-1)
                }
                if(operationType === 'scoreRecordMethod'){
                    this.$set(listObj[length-1],'scoreNum',this.scoreNum5[length-2]-1)
                    
                }else if(operationType === 'editScoreRecord'){
                    this.$set(listObj[length-1],'scoreNum',this.editScoreNum5[length-2]-1)

                }
            }else if(type === 5){
                if(operationType === 'scoreRecordMethod'){
                    this.scoreNum2.push(this.scoreNum2[this.scoreNum2.length-1]-1)
                }else if(operationType === 'editScoreRecord'){
                    this.editScoreNum2.push(this.editScoreNum2[this.editScoreNum2.length-1]-1)
                }
                if(operationType === 'scoreRecordMethod'){
                    this.$set(listObj[length-1],'scoreNum',this.scoreNum2[length-2]-1)
                    
                }else if(operationType === 'editScoreRecord'){
                    this.$set(listObj[length-1],'scoreNum',this.editScoreNum2[length-2]-1)

                }
            }else if(type === 100){
                if(operationType === 'scoreRecordMethod'){
                    this.scoreNum100.push(this.scoreNum100[this.scoreNum100.length-1]+1)
                }else if(operationType === 'editScoreRecord'){
                    this.editScoreNum100.push(this.editScoreNum100[this.editScoreNum100.length-1]+1)
                }
                if(operationType === 'scoreRecordMethod'){
                    this.$set(listObj[length-1],'scoreNum',this.scoreNum100[length-2]+1)
                    
                }else if(operationType === 'editScoreRecord'){
                    this.$set(listObj[length-1],'scoreNum',this.editScoreNum100[length-2]+1)

                }
            }

        }
        else{
          this.$set(listObj[length-1],'scoreNum',list[0])
        }
    },
    // 新增成绩
    addGrade() {
      this.dialogForm.minorGradeRelatedSetDetailsList.push({
        "uniqueId": new Date().getTime(),
        "scoreName": "",
        "scoreMin": "",
        "scoreMax": "",
        "scoreDefault": "",
        "gradePoint": ""
      });
      let newScoreNum5 = [];
      let newScoreNum2 = [];
      let newScoreNum100 = [];
      if(this.dialogMode === 'add'){//新增
          if(this.dialogForm.gradeNameCn === '1002'){//五级制
              newScoreNum5=this.compareArrayList(this.scoreNum5,this.dialogForm.minorGradeRelatedSetDetailsList)
              this.addNewList('scoreRecordMethod',3,newScoreNum5,this.dialogForm.minorGradeRelatedSetDetailsList)
          } else if (this.dialogForm.gradeNameCn === '1003'){//2级制
              newScoreNum2=this.compareArrayList(this.scoreNum2,this.dialogForm.minorGradeRelatedSetDetailsList)
              this.addNewList('scoreRecordMethod',5,newScoreNum2,this.dialogForm.minorGradeRelatedSetDetailsList)
          } else if (this.dialogForm.gradeNameCn === '1001'){//百级制
              newScoreNum100=this.compareArrayList(this.scoreNum100,this.dialogForm.minorGradeRelatedSetDetailsList)
              this.addNewList('scoreRecordMethod',100,newScoreNum100,this.dialogForm.minorGradeRelatedSetDetailsList)
          }
      }
      else if(this.dialogMode === 'edit'){
          if(this.dialogForm.gradeNameCn === '1002'){//五级制
              newScoreNum5=this.compareArrayList(this.editScoreNum5,this.dialogForm.minorGradeRelatedSetDetailsList)
              this.addNewList('editScoreRecord',3,newScoreNum5,this.dialogForm.minorGradeRelatedSetDetailsList)
          } else if (this.dialogForm.gradeNameCn === '1003'){//2级制
              newScoreNum2=this.compareArrayList(this.editScoreNum2,this.dialogForm.minorGradeRelatedSetDetailsList)
              this.addNewList('editScoreRecord',5,newScoreNum2,this.dialogForm.minorGradeRelatedSetDetailsList)
          } else if (this.dialogForm.gradeNameCn === '1001'){//百级制
              newScoreNum100=this.compareArrayList(this.editScoreNum100,this.dialogForm.minorGradeRelatedSetDetailsList)
              this.addNewList('editScoreRecord',100,newScoreNum100,this.dialogForm.minorGradeRelatedSetDetailsList)
          }
      }
    },
    // 删除成绩
    deleteGrade(row) {
      let _this = this
      for (let i = _this.dialogForm.minorGradeRelatedSetDetailsList.length - 1; i >= 0; i--) {
        if (_this.dialogForm.minorGradeRelatedSetDetailsList[i]) {
          if ((_this.dialogForm.minorGradeRelatedSetDetailsList[i].uniqueId && _this.dialogForm.minorGradeRelatedSetDetailsList[i].uniqueId === row.uniqueId) || (_this.dialogForm.minorGradeRelatedSetDetailsList[i].gradeSetDetailsId && _this.dialogForm.minorGradeRelatedSetDetailsList[i].gradeSetDetailsId === row.gradeSetDetailsId)) {
            _this.dialogForm.minorGradeRelatedSetDetailsList.splice(i, 1)
          }
        }
      }
    },
    // 取消
    cancel() {
      this.dialogVisible = false
      this.dialogMode = ''
      Object.keys(this.dialogForm).forEach(key => this.dialogForm[key] = '')
      this.$refs['dialogForm'].clearValidate()
      this.dialogForm.minorGradeRelatedSetDetailsList = []
    },
    // 确定
    confirm() {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          let gradeNameCnArr = this.options.gradeNameCn.filter(value => {
            return value.value === this.dialogForm.gradeNameCn 
          })
          let params = {
            "gradeNameCode": this.dialogForm.gradeNameCn,
            "gradeNameCn": gradeNameCnArr[0].label,
            "gradeNameEn": this.dialogForm.gradeNameEn,
            "gradePassLine": this.dialogForm.gradePassLine,
            "manageDeptId": this.userInfo.currentManageDptId,
            "minorGradeRelatedSetDetailsList": this.dialogForm.minorGradeRelatedSetDetailsList
          }
          if (this.dialogMode === 'add') {
            if (this.dialogForm.hasOwnProperty('gradeSetId')) {
              delete this.dialogForm.gradeSetId
            }
            scoreManagementApi.addScoreRecordMethod(params).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success', 
                  message: this.$t('scoreMangementBase.addSuccessfully')
                })
                this.cancel()
                this.onSubmit()
              }
            })
          } else if (this.dialogMode === 'edit') {
            params['gradeSetId'] = this.dialogForm.gradeSetId
            scoreManagementApi.editScoreRecordMethod(params).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success', 
                  message: this.$t('scoreMangementBase.editSuccessfully')
                })
                this.cancel()
                this.onSubmit()
              }
            })
          }
          
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus();
            }
          }, 1);
        }
      })
    },
    // 重置全局设置
    resetData() {
      // Object.keys(this.globalForm).forEach(key => this.globalForm[key] = [])
      this.$refs['globalForm'].resetFields()
    },
    // 保存全局设置
    saveData() {
      this.$refs['globalForm'].validate(valid => {
        if (valid) {
          let params = []
          for (let key in this.globalForm) {
            if (key !== 'isCheckMsg') {
              params.push({
                "setType": key,
                "setContentCode": this.globalForm[key].toString(),
                "setContentCn": UTILS.translateMultiSelectToStr(this.options[key], this.globalForm[key]),
                "isCheckMsg": this.globalForm.isCheckMsg,
                "manageDeptId": this.userInfo.currentManageDptId
              })
            }
          }
          params.forEach(value => {
            this.globalSetArr.map(element => {
              if (element.setType === value.setType) {
                value['gradeSetGlobalId'] = element.gradeSetGlobalId
                value['manageDeptId'] = element.manageDeptId
              }
            })
          })
          scoreManagementApi.addOrUpdateGlobalSetInfo(params).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: this.$t('scoreMangementBase.savedSuccessfully')
              })
            }
          })
        }
      })
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'scoremanage-ralatedSetting-add') {
              this.permitToAdd = true
            }
            if (item.authCode === 'scoremanage-ralatedSetting-edit') {
              this.permitToDelete = true
            }
            if (item.authCode === 'scoremanage-ralatedSetting-delete') {
              this.permitToEdit = true
            }
            if (item.authCode === 'scoremanage-ralatedSetting-select') {
              this.permitToSelect = true
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
  .score-related-setting-container ::v-deep {
    padding: 0 10px;
    .el-tabs__nav-wrap::after {
      display: none;
    }
    .el-tabs__header {
      margin: 0;
    }
    .el-dialog__body {
      word-break: break-all!important
    }
    .card-margin {
      margin: 0;
    }
    .el-transfer .el-transfer-panel {
      width: 220px;
    }
    .globalForm {
      width: 773px;
    }
  }
</style>
